


import React, { useEffect,  useCallback } from 'react';
import Taro from '@tarojs/taro';
import { View ,Text,Image, Input, Block } from '@tarojs/components';
import useFetchRequest from '../../common/useFetchRequest';
import './index.scss';

export default function SearchBar(props) {
  const { getNavigatorExtra, state, setAction,request,previewImg,formatDate,getFileImg,setUpdate } = useFetchRequest();
  const { salesList=[],  } = state

  // salesGoods
  const getReportingList = useCallback(params => {
    request({
      url: 'reportingSaleProductList',
      data: params,
      callback: res => {
        res.success && setUpdate(
          setAction({ salesList: res.models })
        );
      },
    });
     // eslint-disable-next-line
  }, []);

  // salesData
  const getInstantList = (res)=>{
    const timeList = [];
    if(Array.isArray(res.models)){
      res.models.forEach(i => {
        const isAlive = timeList.find(t => t.time === i.saleTime);
        if (isAlive) {
          isAlive.list.push(i);
          isAlive.amount += i.totalSaleAmount;
          isAlive.quantity += i.totalSaleQuantity;
        } else {
          timeList.push({
            time: i.saleTime,
            list: [i],
            amount: i.totalSaleAmount,
            quantity: i.totalSaleQuantity,
          });
        }
      })
    }
    return timeList
  }

  // 获取列表数据
  const getInstantItemList = useCallback(params => {
    request({
      url: 'saleInstantItemList',
      data: params,
      callback: res => {
        const timeList = getInstantList(res)
        res.success && setAction({ salesList: timeList });
        setUpdate();
      },
    });
    // eslint-disable-next-line
  }, []);

  useEffect(()=>{
    const params = getNavigatorExtra(props.tid)
    setUpdate(setAction({...params}))
    // eslint-disable-next-line
  },[props.tid])

  const onInput = (e)=>{
    setAction({ search: e.detail.value })
  }

  const onConfirm = ()=>{
    const params = {}
    const query = getNavigatorExtra(props.tid)
    const name= query.keyword || 'keyword'
    params[name] = state.search
    if(query.page === 'salesData'){
      getInstantItemList({condition:{...query, ...params}})
    }
    if(query.page === 'salesGoods'){
      getReportingList({condition:{...query, ...params}})
    }

  }

  const onCancel = ()=>{
    Taro.navigateBack({ })
  }


  console.log(salesList)

  return (
    <Block>
      <View className='search-page'>
        <View className='input-bar'>
          <Input className='input' autoFocus placeholder='请输入货品名称' onInput={onInput}  onConfirm={onConfirm} cle />
          <View className='btn' onClick={onCancel}>取消</View>
        </View>
      </View>
      {
        state.page === 'salesData' &&
        (<Block>
          {
            salesList.map((goods,index) => (
              <View className='card-bar' key={index}>
                <View className='card-title'>
                  <Text className='time'>{formatDate('yyyy-MM-dd', goods.time)}</Text>
                  <Text className='total'>
                    合计:<Text className='value'>{goods.quantity}件</Text>
                    收入:<Text className='value'>￥{goods.amount}</Text>
                  </Text>
                </View>
                {
                  goods.list && goods.list.map((item,i) =>(
                    <View key={i} onClick={()=>{Taro.navigateTo({url:'/pages/gateManage/salesData/detail?saleRecordId='+item.id})}}>
                      <View className='card-goods'>
                        <Image
                          className='goods-img icon-img-bg'
                          src={getFileImg({fileId:item.productCoverId,fileCode:item.productCoverCode})}
                          onClick={previewImg.bind(null,getFileImg({fileId:item.productCoverId,fileCode:item.productCoverCode}))}
                        />
                        <View className='goods-info'>
                          <View className='title ft-30'>{item.productName}</View>
                          <View className='info'>订单编号:{item.stallOrderNo}</View>
                          <View className='info'>
                            上报时间:{formatDate('yyyy-MM-dd hh:mm', item.saleRecordTime)}
                          </View>
                        </View>
                        <View className='total'>
                          <View className='quantity ft-26'>x {item.totalSaleQuantity}</View>
                          <View className='price ft-28'>￥ {item.totalSaleAmount}</View>
                        </View>
                      </View>

                    </View>
                  ))
                }
              </View>
            ))
          }
        </Block>)
      }

      {
        state.page === 'salesGoods' &&
        (<Block>
          {salesList.map((goods,index) => (
            <View key={index} onClick={()=>{Taro.navigateTo({url:'/pages/gateManage/salesData/history?stallOrderId='+ goods.stallOrderId})}}>
              <View className='product-card'>
                <View className='product-goods'>
                  <View className='product-info'>
                    <Image
                      className='goods-img icon-img-bg'
                      src={getFileImg({fileId:goods.productCoverId,fileCode:goods.productCoverCode })}
                      onClick={previewImg.bind(null,getFileImg({fileId:goods.productCoverId,fileCode:goods.productCoverCode }))}
                    />
                    <View className='goods-info'>
                      <View className='info'>{goods.productName}</View>
                      <View className='info'>订单编号 {goods.stallOrderNo}</View>
                      <View className='info'>{formatDate('yyyy-MM-dd', goods.arriveTime)} 到货</View>
                    </View>
                  </View>
                  <View className='goods-spec ft-26'>
                    { goods.saleRecordItemList && goods.saleRecordItemList.map((item,i) => (
                      <View className='spec-item' key={i}>
                        <Text className='label'>{item.productSpec}</Text>
                        <Text className='value'>{(item.reservedQuantity - item.saleQuantity)||0} 件待销售</Text>
                      </View>
                    ))}
                  </View>
                </View>
              </View>
            </View>
          ))}
        </Block>)
      }
    </Block>
  );
}
